#!/usr/bin/env python
# coding: utf-8


import os,shutil
import time,datetime
import wave
import numpy as np
import warnings
import pandas as pd
import collections
import json

warnings.filterwarnings("ignore")


class Intimacy_sys():
    '''
    亲密度系统(Intimacy system)
    目前有三种亲密层次：陌生人（<20）、朋友(21-60)和家人(>60)
    每天都会重新计算亲密度
    把所有要用到的数据都保存到文件中，供以递增亲密系统使用
    '''
    #def __init__(self, picture_path, audio_path):
    def __init__(self):
        #self.picture_path= picture_path
        self.now_date =  time.strftime('%Y-%m-%d',time.localtime(time.time()))
        self.face_path = 'faces.log'
        tree=lambda:collections.defaultdict(tree)
        self.Inti_dict = tree()
        self.Inti = tree()
        self.audio_path = 'audio_wav_a5'

    def get_speaker_times(self):
        '''
        从声纹返回结果或者信息
        以声纹库中每个主人音频的数量作分数，获取总音频数量与当日创建的音频数量
        把信息都保存到Inti_dict中
        '''
        for name in os.listdir(self.audio_path):
            if name != 'unknown':
                people_path = os.path.join(self.audio_path,name)
                audio_now_num = 0
                for audio in os.listdir(people_path):
                    audio_file = os.path.join(people_path, audio)
                    timestamp = os.path.getmtime(audio_file)
                    date = time.strftime('%Y-%m-%d',time.localtime(timestamp)) #获取当前文件最近修改时间
                    if self.now_date == date:
                        audio_now_num = audio_now_num + 1
                        #print([audio_file, audio_file_date])
                #根据总次数划分等级，不同等级加不同分
                if len(os.listdir(people_path)) > 180 : spe_le = 2
                elif len(os.listdir(people_path)) > 90 : spe_le = 1.5
                elif len(os.listdir(people_path)) > 30 : spe_le = 1
                elif len(os.listdir(people_path)) > 0 : spe_le = 0.5
                else : spe_le = 0
                
                if audio_now_num > 30 : spe_today_le = 2
                elif audio_now_num > 18 : spe_today_le = 1.5
                elif audio_now_num > 6 : spe_today_le = 1
                elif audio_now_num > 0 : spe_today_le = 0.5
                else : spe_today_le = 0
                self.Inti_dict[name]['speaker_all_times'] = len(os.listdir(people_path))
                self.Inti_dict[name]['speaker_all_times_le'] = spe_le
                self.Inti_dict[name]['speaker_day_times'] = audio_now_num
                self.Inti_dict[name]['speaker_day_times_le'] = spe_today_le
                #self.audio_Inti.append([name,len(os.listdir(people_path)), spe_le, audio_now_num, spe_today_le])
                # [主人姓名，主人总音频数量，主人总音频数量等级，主人当日音频数量, 主人当日音频数量等级分数]      
        #print(json.dumps(self.Inti_dict))
        
    def face_sys(self):
        '''
        获取人脸识别信息,未完成
        以人脸识别库中每个主人人脸出现的的数量作分数
        同时计算当天人脸出现的数量
        self.face_Inti，信息为：[主人姓名，主人总人脸数量，主人当日人脸数量] 
        '''
        
        face_list = []
        with open(self.face_path, 'r' ,encoding = 'utf-8') as f:
            lines = f.readlines()
            #print(len(lines))
        f.close()
        #print(len(lines))
        for line in lines:
            face_list.append([line.split(' ')[0], line.split(' ')[1].split(',')[0], 
                             line.split(' ')[3].split('\t')[0], line.split(' ')[3].split('\t')[1],
                             line.split(' ')[4].split('\n')[0]])
            
        #print(face_list)
        face_frame = pd.DataFrame(face_list, columns = ['date', 'time','name',  'date2' , 'timing'])
        for name in face_frame['name'].unique():
            if name != 'unknown':
                #print(name)
                frame_name = face_frame[face_frame['name'] == name]
                if len(frame_name) > 180 : face_le = 4
                elif len(frame_name) > 90 : face_le = 3
                elif len(frame_name) > 30 : face_le = 2
                elif len(frame_name) > 0 : face_le = 1
                else : face_le = 0
                #print(self.now_date)
                frame_date = frame_name[frame_name['date'] == self.now_date]
                #print( face_frame['date'] )
                if len(frame_date) > 30 : face_today_le = 4
                elif len(frame_date) > 18 : face_today_le = 3
                elif len(frame_date) > 6 : face_today_le = 2
                elif len(frame_date) > 0 : face_today_le = 1
                else : face_today_le = 0

                #print(len(frame_date))
                self.Inti_dict[name]['face_all_times'] = len(frame_name)
                self.Inti_dict[name]['face_all_times_le'] = face_le
                self.Inti_dict[name]['face_day_times'] = len(frame_date)
                self.Inti_dict[name]['face_day_times_le'] = face_today_le
                #self.face_Inti.append([name, len(frame_name),face_le, len(frame_date), face_today_le])
                # [主人姓名，主人总人脸数量，主人总人脸数量等级，主人当日人脸数量, 主人当日人脸数量等级分数]  
        #print(self.face_Inti)
        
    def asr_talk(self):
        '''
        说亲昵内容次数（如：喜欢你、你好可爱等表达赞美与爱意的语句）。通过语音识别，把关键词获取下来。只要有一次就递增。这里只计算总次数
        这里也要计算当日次数。
        
        '''
        a = ['linkunling', 22, 2, 20, 2]
        self.asr_times.append(a)
        a = ['lilili', 0, 0, 0, 0]
        self.asr_times.append(a)
        a = ['lingli',8, 1, 7, 1]
        self.asr_times.append(a)
        a = ['liusong_a5',0, 0, 0,  0]
        self.asr_times.append(a)
        a = ['xiefei_a5',3, 0.5, 3, 0.5]
        self.asr_times.append(a)
        
        #print(self.asr_times)
        
    def love_score(self):
        '''
        该函数是计算每位主人当日接触次数
        '''
        self.get_speaker_times()
        self.face_sys()
        #print(json.dumps(self.Inti_dict))
        #self.asr_talk() # 还没有完善 先不加进去
        #这里只计算了说话人识别和人脸识别。没有加上语音识别
        
        #计算当日语音和人脸次数，以此判断主人当日是否接触机器人
        for name_num in range(len(self.Inti_dict)):
            name = list(self.Inti_dict.keys())[name_num]
            #print(name)

            #计算每日次数以及每日次数对应的等级（多元线性）
            if 'speaker_day_times' in self.Inti_dict[name] :
                #print('run high')
                speaker_day_times = self.Inti_dict[name]['speaker_day_times']
            else : speaker_day_times = 0
            if  'face_day_times' in self.Inti_dict[name] :
                #print('run high2')
                face_day_times = self.Inti_dict[name]['face_day_times']
            else : face_day_times = 0

            #print(self.Inti_dict[name])
            #print(self.Inti_dict[name]['speaker_day_times'] )
            #print(json.dumps(self.Inti_dict))
            #print(self.Inti_dict[name]['face_day_times'],self.Inti_dict[name]['speaker_day_times'] )     
            day_times = speaker_day_times + face_day_times
            self.Inti_dict[name]['all_day_times'] = day_times
            if day_times >30 : day_times_le = 2
            elif day_times > 10 : day_times_le = 1.5
            elif day_times > 5 : day_times_le = 1
            elif day_times > 0 : day_times_le = 0.5
            else : day_times_le = -1
            self.Inti_dict[name]['all_day_times_le'] = day_times_le
            #计算每日次数等级，以及累加对应的等级（递增计算）
            if 'speaker_day_times_le' in self.Inti_dict[name]:
                audio_day_times_le = self.Inti_dict[name]['speaker_day_times_le']
            else : audio_day_times_le = 0
            if  'face_day_times_le' in self.Inti_dict[name]:
                face_day_times_le = self.Inti_dict[name]['face_day_times_le']
            else : face_day_times_le = 0
#             if  self.Inti_dict[name]['asr_day_times_le'] == True:
#                 asr_day_times_score = self.Inti_dict[name]['asr_day_times_le']
#             else : face_day_times_score = 0
           # day_times_score = audio_day_times_score + face_day_times_score + asr_day_times_score
            day_times_score = audio_day_times_le + face_day_times_le
            
            if day_times_score  >6 : day_times_score_le = 2
            elif day_times_score  > 4 : day_times_score_le  = 1.5
            elif day_times_score > 2 : day_times_score_le  = 1
            elif day_times_score  > 0 : day_times_score_le  = 0
            else : day_times_score_le  = -1
            
            #计算多元线性方程，比例是5：10：3：2
            if 'speaker_all_times' in self.Inti_dict[name]:
                speaker_all_times = self.Inti_dict[name]['speaker_all_times']
            else :speaker_all_times = 0
            if 'face_all_times' in self.Inti_dict[name]:
                face_all_times = self.Inti_dict[name]['face_all_times']
            else :face_all_times = 0
            #y_times = 0.25*audio_day_times_score + 0.5*frame['face_all_times'][i] + 0.15*frame['asr_times'][i] + 0.1*frame['day_times'][i]
            y_times = 0.25*speaker_all_times + 0.5*face_all_times + 0.1*day_times
            
            #计算次数每日递增，这里递增是根据每日出现的次数划分等级的。
            if 'face_all_times_le' in self.Inti_dict[name]:
                face_all_times_le = self.Inti_dict[name]['face_all_times_le']
            else : face_all_times_le= 0
            if 'speaker_day_times_le' in self.Inti_dict[name]:
                speaker_day_times_le = self.Inti_dict[name]['speaker_day_times_le']
            else : speaker_day_times_le= 0    
            y_le = face_all_times_le +  speaker_day_times_le  + day_times_score_le
            
            #print(name, y_times, y_le)
            #把以上两个公式计算出来的亲密度添加到字典中
            self.Inti[name]['times_score'] = y_times
            self.Inti[name]['level_score'] = y_le
            
        #把亲密度信息保存到json文件中

        #os.remove('inti_info.json')
        #print(json.dumps(self.Inti_dict))
        #print(self.Inti_dict)
        json_str = json.dumps(self.Inti_dict)
        #print(json_str)
        with open('inti_info.json', 'w') as json_file:
            json_file.write(json_str)

        json_str2 = json.dumps(self.Inti)
        #print(json_str2)
        with open('inti_score.json', 'w') as json_file2:
            json_file2.write(json_str2)



if __name__ == '__main__':
    love_sys = Intimacy_sys()
    love_sys.love_score()







